<?php

namespace app\api\controller;

use app\common\controller\Api;
use fast\Http;
use app\common\exception\UploadException;
use app\common\library\Upload;
use fast\Random;
use getID3;
use think\Db;

/**
 * 歌曲接口
 */
class Music extends Api
{
    protected $noNeedLogin = ['addSong'];
    protected $noNeedRight = '*';


    public function addSong($id){
        $attachment = null;
        //默认普通上传文件
        $file = $this->request->file('file');
        try {
            $upload = new Upload($file);
            $attachment = $upload->upload('song/');

            // 获取 POST 参数
            $album_id = $this->request->post('album_id');// 专辑 ID  暂时不绑定

            // 生成随机 song_id
            $song_id = $id ? $id : Random::alnum(16);

            // 获取音频文件时长
            $duration = 0;
            // 使用上传后的文件路径，而不是临时文件路径
            $uploadedFilePath = ROOT_PATH . 'public' . $attachment->url;
            
            if (class_exists('getID3') && file_exists($uploadedFilePath)) {
                $getID3 = new getID3();
                $fileInfo = $getID3->analyze($uploadedFilePath);
                if (isset($fileInfo['playtime_seconds'])) {
                    $duration = (int)round($fileInfo['playtime_seconds']);
                }
            }

            $newCommon = new Common();
            $img = $newCommon->getSongImage($id);

            // 处理歌曲名称
            $originalName = $file->getInfo('name');
            // 去掉文件后缀
            $nameWithoutExt = pathinfo($originalName, PATHINFO_FILENAME);
            
            // 通过'-'切割
            $parts = explode('-', $nameWithoutExt);
            
            $songName = '';
            $artistName = '';
            
            if (count($parts) >= 2) {
                // 有歌手和歌曲名
                $artistName = trim($parts[0]);
                $songName = trim($parts[1]);
            } else {
                // 只有歌曲名
                $songName = trim($nameWithoutExt);
            }
            
            $artistId = Db::name('artist')->where('name', $artistName)->value('id');
            if (!$artistId) {
                $artistId = Db::name('artist')->insertGetId([
                    'name' => $artistName,
                    'artist_id' => Random::alnum(16),
                    'avatar' => $img,
                    'createtime' => time(),
                    'updatetime' => time(),
                    'status' => 1,
                ]);
            }

            
            // 保存到数据库
            $data = [
                'song_id' => $song_id,
                'name' => $songName,
                'album_id' => $album_id,
                'album_name' => $artistName,
                'album_image' => $img,
                'url_file' => $attachment->url,
                'duration' => $duration,
                'createtime' => time(),
                'updatetime' => time(),
                'weigh' => 1,
            ];

            // 插入数据库
            $songModel = new \app\admin\model\Song();

            $songinfo = $songModel->where('name', $data['name'])->find();
            if (!$songinfo) {
                $songId = $songModel->insertGetId($data);
                // 创建绑定
                Db::name('song_artist')->insert([
                    'song_id' => $songId,
                    'artist_id' => $artistId,
                    'createtime' => date('Y-m-d H:i:s'),
                ]);
            }
            $this->success('上传成功', $data);
        } catch (UploadException $e) {
            $this->error($e->getMessage());
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }


    /**
     * 获取用户历史记录
     *
     * @param string $uid 用户ID
     * @param int $timestamp 时间戳
     * @param int $type 类型
     * @return void
     */
    public function record()
    {
        $uid = $this->auth->id;
        $timestamp = $this->request->get('timestamp', time(), 'int');
        $type = $this->request->get('type', 0, 'int');
        
        // 从数据库获取用户历史记录
        $allData = [];
        
        // 查询用户历史记录
        $records = \think\Db::query("
            SELECT 
                s.id as id, 
                s.name, 
                s.album_image as picUrl, 
                GROUP_CONCAT(a.name SEPARATOR ',') as artist_names,
                GROUP_CONCAT(a.avatar SEPARATOR ',') as artist_avatars
            FROM 
                mu_user_history uh
            JOIN 
                mu_song s ON uh.song_id = s.id
            LEFT JOIN 
                mu_song_artist sa ON s.song_id = sa.song_id
            LEFT JOIN 
                mu_artist a ON sa.artist_id = a.artist_id
            WHERE 
                uh.user_id = :user_id 
                AND uh.type = :type
                AND uh.createtime <= :timestamp
            GROUP BY 
                s.song_id, s.name, s.album_image, uh.playtime
            ORDER BY 
                uh.playtime DESC
        ", ['user_id' => $uid, 'type' => $type, 'timestamp' => $timestamp]);
        
        // 格式化数据
        foreach ($records as $record) {
            $artists = explode(',', $record['artist_names']);
            $ar = [];
            foreach ($artists as $artist) {
                $ar[] = ['name' => $artist];
            }
            
            $allData[] = [
                'song' => [
                    'id' => $record['id'],
                    'name' => $record['name'],
                    'al' => [
                        'picUrl' => cdnurl($record['picUrl'], true)
                    ],
                    'ar' => $ar
                ]
            ];
        }
        
        $this->success('获取成功', [
            'allData' => $allData
        ]);
    }

    /**
     * 获取用户歌单列表
     *
     * @param string $uid 用户ID
     * @param int $timestamp 时间戳
     * @return void
     */
    public function playlist()
    {
        $uid = $this->request->get('uid', '');
        $timestamp = $this->request->get('timestamp', time(), 'int');
        
        // 从数据库获取用户歌单列表
        $playlists = \think\Db::query("
            SELECT 
                p.playlist_id as id,
                p.name,
                p.cover_image as coverImgUrl,
                p.description,
                (SELECT COUNT(*) FROM mu_playlist_song ps WHERE ps.playlist_id = p.playlist_id) as trackCount,
                (SELECT JSON_ARRAYAGG(JSON_OBJECT('id', ps.song_id)) 
                 FROM mu_playlist_song ps 
                 WHERE ps.playlist_id = p.playlist_id) as trackIds
            FROM 
                mu_playlist p
            WHERE 
                p.user_id = :user_id
                AND p.createtime <= :timestamp
            ORDER BY 
                p.updatetime DESC
        ", ['user_id' => $uid, 'timestamp' => $timestamp]);
        
        // 处理 JSON 字符串
        foreach ($playlists as &$playlist) {
            if (isset($playlist['trackIds'])) {
                $playlist['trackIds'] = json_decode($playlist['trackIds'], true);
            } else {
                $playlist['trackIds'] = [];
            }
        }
        
        $this->success('获取成功', [
            'playlist' => $playlists
        ]);
    }

    /**
     * 获取播放列表详细信息
     *
     * @param int $id 播放列表ID
     * @param int $timestamp 时间戳
     * @return void
     */
    public function detail()
    {
        $id = $this->request->get('id', '');
        $timestamp = $this->request->get('timestamp', time(), 'int');
        
        // 从数据库获取播放列表详细信息
        $playlist = \think\Db::query("
            SELECT 
                p.playlist_id,
                p.name,
                p.cover_image as coverImgUrl,
                p.description,
                u.username as creator_name,
                u.avatar as creator_avatar,
                (SELECT JSON_ARRAYAGG(JSON_OBJECT('id', ps.song_id)) 
                 FROM mu_playlist_song ps 
                 WHERE ps.playlist_id = :id) as trackIds
            FROM 
                mu_playlist p
            LEFT JOIN 
                mu_user u ON p.user_id = u.user_id
            WHERE 
                p.playlist_id = :id
                AND p.createtime <= :timestamp
            LIMIT 1
        ", ['id' => $id, 'timestamp' => $timestamp]);
        
        if (empty($playlist)) {
            $this->error('播放列表不存在');
        }
        
        $playlistData = $playlist[0];
        
        // 处理 JSON 字符串
        if (isset($playlistData['trackIds'])) {
            $playlistData['trackIds'] = json_decode($playlistData['trackIds'], true);
        } else {
            $playlistData['trackIds'] = [];
        }
        
        // 添加创建者信息
        $playlistData['creator'] = [
            'nickname' => $playlistData['creator_name'] ?? '未知用户',
            'avatarUrl' => $playlistData['creator_avatar'] ?? ''
        ];
        
        // 移除多余字段
        unset($playlistData['creator_name'], $playlistData['creator_avatar']);
        
        $this->success('获取成功', [
            'playlist' => $playlistData
        ]);
    }

    /**
     * 获取歌曲详细信息
     *
     * @param string $ids 歌曲ID，多个ID用逗号分隔
     * @return void
     */
    public function detailinfo()
    {
        $ids = $this->request->get('ids', '');
        
        // 将逗号分隔的ID字符串转换为数组
        $idArray = explode(',', $ids);
        
        // 构建 IN 查询的参数
        $placeholders = implode(',', array_fill(0, count($idArray), '?'));
        
        // 从数据库获取歌曲详细信息
        $songs = \think\Db::query("
            SELECT 
                s.song_id as id,
                s.name,
                JSON_OBJECT('id', s.album_id, 'name', s.album_name, 'picUrl', s.album_image) as al,
                (SELECT JSON_ARRAYAGG(JSON_OBJECT('id', a.artist_id, 'name', a.name)) 
                 FROM mu_song_artist sa 
                 JOIN mu_artist a ON sa.artist_id = a.artist_id 
                 WHERE sa.song_id = s.song_id) as ar,
                s.duration
            FROM 
                mu_song s
            WHERE 
                s.song_id IN ($placeholders)
        ", $idArray);
        
        // 处理 JSON 字符串
        foreach ($songs as &$song) {
            if (isset($song['al'])) {
                $song['al'] = json_decode($song['al'], true);
            } else {
                $song['al'] = ['id' => '', 'name' => '', 'picUrl' => ''];
            }
            
            if (isset($song['ar'])) {
                $song['ar'] = json_decode($song['ar'], true);
            } else {
                $song['ar'] = [];
            }
        }
        
        $this->success('获取成功', [
            'songs' => $songs
        ]);
    }

    /**
     * 获取歌曲的详细信息及播放URL，并记录用户播放历史
     *
     * 根据请求中的歌曲ID查询数据库，返回歌曲的基本信息、播放URL、文件大小、比特率等数据。
     * 同时记录用户的播放历史到mu_user_history表中。
     * 如果歌曲不存在，返回错误信息。
     *
     * @return void
     * @throws \think\exception\HttpResponseException 当歌曲不存在时抛出错误
     */
    public function url(){
        $id = $this->request->get('id', '');
        $uid = $this->auth->id;
        $info = Db::name('song')->where('id', $id)->find();
        
        if (!$info) {
            $this->error('歌曲不存在');
        }
        
        // 记录用户播放历史
        if (empty($uid)) {
            $now = time();
            $historyData = [
                'user_id' => $uid,
                'song_id' => $id,
                'type' => '0', // 0=播放历史
                'playtime' => date('Y-m-d H:i:s'), // 当前时间，格式化为datetime
                'createtime' => $now // 当前时间戳
            ];

            $his = Db::name('user_history')->where('song_id', $id)->where('user_id', $uid)->find();
            if ($his) {
                $historyData['playtime'] = date('Y-m-d H:i:s', $his['createtime']);
                $historyData['createtime'] = $his['createtime'];
                Db::name('user_history')->where('song_id', $id)->where('user_id', $uid)->update($historyData);
            }else{
                Db::name('user_history')->insert($historyData);
            }
        }
        
        $url = cdnurl($info['url_file'], true);
        $fileSize = file_exists(ROOT_PATH . 'public' . $info['url_file']) ? filesize(ROOT_PATH . 'public' . $info['url_file']) : 0;
        
        $data = [
            [
                'id' => intval($info['id']),// 歌曲ID
                'name' => $info['name'], // 歌曲名称
                'ar' => [], // 歌手信息，暂时为空
                'url' => $url, // 歌曲URL
                'br' => 320000,// 比特率，单位为bps
                'size' => $fileSize, // 文件大小，单位为字节
                'md5' => md5_file(ROOT_PATH . 'public' . $info['url_file']) ?: '',
                'type' => pathinfo($info['url_file'], PATHINFO_EXTENSION) ?: 'mp3',
                'level' => 'standard',// 音质等级
                'encodeType' => 'mp3',// 编码类型
                'time' => intval($info['duration']) * 1000, // 歌曲时长，单位为毫秒
                'payed' => 0,// 是否付费
                'fee' => 0,// 费用，单位为分
                'gain' => 0,// 增益
                'freeTrialInfo' => null, // 免费试听信息
                'freeTimeTrialInfo' => null,// 免费时长试听信息
                'urlSource' => 0// URL来源，0表示未知
            ]
        ];
        
        $this->success('获取成功', $data);
    }

    /**
     * 获取歌词信息
     *
     * @param string $id 歌曲ID
     * @return void
     */
    public function lyric(){
        $id = $this->request->get('id', '');
        $info = Db::name('song')->where('id',$id)->find();
        
        if (!$info) {
            $this->error('歌曲不存在');
        }
        
        // 查询歌词表
        // $lyric = Db::name('lyric')->where('song_id',$id)->find();
        $lyric = false;
        
        // 如果没有找到歌词，返回静态数据
        if (!$lyric) {
            // 返回静态示例数据
            $this->success('获取成功', [
                'lrc' => [
                    'version' => 1,
                    'lyric' => "[00:00.000] 作词 : 未知
[00:01.000] 作曲 : 未知
[00:10.100] 暂无歌词
"
                ],
                'tlyric' => [
                    'version' => 1,
                    'lyric' => ""
                ],
                'klyric' => [
                    'version' => 1,
                    'lyric' => ""
                ]
            ]);
        } else {
            // 返回数据库中的歌词
            $this->success('获取成功', [
                'lrc' => [
                    'version' => 1,
                    'lyric' => $lyric['lyric'] ?? "[00:00.000] 作词 : 未知
[00:01.000] 作曲 : 未知
[00:10.100] 暂无歌词
"
                ],
                'tlyric' => [
                    'version' => 1,
                    'lyric' => $lyric['tlyric'] ?? ""
                ],
                'klyric' => [
                    'version' => 1,
                    'lyric' => ""
                ]
            ]);
        }
    }

    public function likelist(){
        $ids = Db::name('song')->column('id');
        $this->success('获取成功', $ids);
    }
}